package com.zxy.leetcode.lcof;

import com.zxy.leetcode.common.ListNode;
import com.zxy.leetcode.common.ListNodeHelper;

import java.util.Arrays;

/**
 * https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
 *
 * 从尾到头打印链表
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 */
public class Test06 {

    public static void main(String[] args) {
        Test06 test = new Test06();

        ListNode head = ListNodeHelper.build(5);
        ListNodeHelper.print(head);

        System.out.println(Arrays.toString(test.reversePrint(head)));
    }

    public int[] reversePrint(ListNode head) {
        if (head == null) {
            return new int[0];
        }

        ListNode tail = head;
        int count = 0;
        while(tail != null) {
            count ++;
            tail = tail.next;
        }

        int[] nums = new int[count];

        tail = head;
        int index = count;
        while(tail != null) {
            index --;
            nums[index] = tail.val;
            tail = tail.next;
        }
        return nums;
    }

}
